package com.wjf.accesscontrol.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Base64;
import android.util.Log;

public class ToolFun {

    public static int asc_hex(byte[] asc, byte[] hex, int asclen) {
        String ss = new String(asc);
        int string_len = ss.length();
        int len = asclen; // int len = asclen/2;
        if (string_len % 2 == 1) {// if(asclen%2 ==1){
            ss = "0" + ss;
            len++;
        }
        for (int i = 0; i < len; i++) {
            hex[i] = (byte) Integer.parseInt(ss.substring(2 * i, 2 * i + 2), 16);
        }
        return 0;
    }

    public static int hex_asc(byte[] hex, byte[] asc, int blen) {
        for (int i = 0; i < blen; i++) {
            byte temp = (byte) (hex[i] & 0xf0);
            if (temp < 0) {
                temp = (byte) (hex[i] & 0x70);
                temp = (byte) ((byte) (temp >> 4) + 0x08);
            } else {
                temp = (byte) (hex[i] >> 4);
            }

            if ((temp >= 0) && (temp <= 9)) {
                asc[i * 2 + 0] = (byte) ((byte) temp + '0');
            } else if ((temp >= 10) && (temp <= 15)) {
                asc[i * 2 + 0] = (byte) ((byte) temp + 'A' - 10);
            } else {
                asc[i * 2 + 0] = '0';
            }

            temp = (byte) (hex[i] & 0x0f);
            if ((temp >= 0) && (temp <= 9)) {
                asc[i * 2 + 1] = (byte) ((byte) temp + '0');
            } else if ((temp >= 10) && (temp <= 15)) {
                asc[i * 2 + 1] = (byte) ((byte) temp + 'A' - 10);
            } else {
                asc[i * 2 + 1] = '0';
            }
        }
        return 0;
    }

    public static int hex_asc(byte[] hex, int hexPos, byte[] asc, int blen) {
        for (int i = hexPos; i < hexPos + blen; i++) {
            byte temp = (byte) (hex[i] & 0xf0);
            if (temp < 0) {
                temp = (byte) (hex[i] & 0x70);
                temp = (byte) ((byte) (temp >> 4) + 0x08);
            } else {
                temp = (byte) (hex[i] >> 4);
            }

            if ((temp >= 0) && (temp <= 9)) {
                asc[(i - hexPos) * 2 + 0] = (byte) ((byte) temp + '0');
            } else if ((temp >= 10) && (temp <= 15)) {
                asc[(i - hexPos) * 2 + 0] = (byte) ((byte) temp + 'A' - 10);
            } else {
                asc[(i - hexPos) * 2 + 0] = '0';
            }

            temp = (byte) (hex[i] & 0x0f);
            if ((temp >= 0) && (temp <= 9)) {
                asc[(i - hexPos) * 2 + 1] = (byte) ((byte) temp + '0');
            } else if ((temp >= 10) && (temp <= 15)) {
                asc[(i - hexPos) * 2 + 1] = (byte) ((byte) temp + 'A' - 10);
            } else {
                asc[(i - hexPos) * 2 + 1] = '0';
            }
        }
        return 0;
    }

    public static int cr_bcc(final int len, final byte[] data) {
        int temp = 0, i;
        for (i = 0; i < len; i++) {
            temp = temp ^ data[i];
        }
        return temp;
    }

    public static void splitFun(byte usplitdata[], byte ulen, byte splitdata[], byte slen) {
        // cmddata
        for (int nI = 0, nJ = 0; nI < ulen * 2; nI = nI + 2, nJ++) {
            splitdata[nI] = (byte) (((usplitdata[nJ] & 0xF0) >> 4) + 48);
            splitdata[nI + 1] = (byte) ((usplitdata[nJ] & 0x0F) + 48);
        }
    }

    public static int GetIntLen(byte byLenH, byte byLenL) {
        // TODO Auto-generated method stub
        int highLen = byLenH;
        if (highLen < 0) {
            highLen = highLen + 256;
        }
        int lowLen = byLenL;
        if (lowLen < 0) {
            lowLen = lowLen + 256;
        }
        return highLen * 256 + lowLen;
    }

    public static byte[] getHignAndLowByte(int st) {
        st = st < 0 ? ~st + 1 : st;
        byte[] retByte = new byte[2];
        retByte[0] = (byte) ((st & 0xFF00) >> 8);
        retByte[1] = (byte) ((st & 0x00FF));
        return retByte;
    }

    public static byte getUnsigedByte(byte sdata) {
        return (byte) (sdata < 0 ? sdata + 256 : sdata);
    }

    public static String PrintBuffer(byte[] bufData) {
        String str = "";
        int printLen = (bufData.length < 1000 ? bufData.length : 1000);
        for (int i = 0; i < printLen; i++) {
            str = str + String.format("%02X", bufData[i]) + " ";
        }
        return str;
    }

    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    public static int stringToInt(String intstr) {
        if (intstr.isEmpty()) {
            return 0;
        }
        Integer integer;
        integer = Integer.valueOf(intstr);
        return integer.intValue();
    }

    public static boolean checkWriteData(String strwrite) {
        boolean bPass = false;
        byte[] writeData = strwrite.toUpperCase().getBytes();
        for (int i = 0; i < writeData.length; i++) {
            if ((0x30 <= writeData[i] && writeData[i] <= 0x39) || ('A' <= writeData[i] && writeData[i] <= 'F')) {
                bPass = true;
            } else {
                bPass = false;
            }
        }
        return bPass;
    }

    public static void copyFileFromAssets(Context context, String assetsFilePath, String targetFileFullPath)
            throws IOException {

        InputStream assestsFileImputStream;
        // try {
        assestsFileImputStream = context.getAssets().open(assetsFilePath);
        copyFile(assestsFileImputStream, targetFileFullPath);
        // } catch (IOException e) {
        // LogMg.d("Tag", "copyFileFromAssets " + "IOException-" +
        // e.getMessage());
        // e.printStackTrace();
        // }
    }

    private static void copyFile(InputStream in, String targetPath) throws IOException {
        // try {
        FileOutputStream fos = new FileOutputStream(new File(targetPath));
        byte[] buffer = new byte[1024];
        int byteCount = 0;
        while ((byteCount = in.read(buffer)) != -1) {// ѭ������������ȡ
            // buffer�ֽ�
            fos.write(buffer, 0, byteCount);// ����ȡ��������д�뵽�����
        }
        fos.flush();// ˢ�»�����
        in.close();
        fos.close();
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
    }

    private static boolean isFileByName(String string) {
        if (string.contains(".")) {
            return true;
        }
        return false;
    }

    public static void initLicData(Context context, String workPath) {
        File file = new File(workPath);
        if (!file.exists()) {
            file.mkdirs();
            try {
                String[] listFiles = context.getAssets().list("");
                for (String s : listFiles) {
                    if (isFileByName(s)) {// �ļ�
                        copyFileFromAssets(context, s, workPath + "/" + s);
                    }
                }
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                if (file.exists()) {
                    file.delete();
                }
                e1.printStackTrace();
            }
        }

    }

    /**
     * 将Base64编码转换为图片
     *
     * @param base64Str
     * @param path
     * @return true
     */
    public static boolean base64ToFile(String base64Str, String path) {
        byte[] data = Base64.decode(base64Str, Base64.NO_WRAP);
        for (int i = 0; i < data.length; i++) {
            if (data[i] < 0) {
                //调整异常数据
                data[i] += 256;
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(path);
            os.write(data);
            os.flush();
            os.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String getInNetIp(Context context) {
        // 获取wifi服务
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        // 判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }

        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        String ip = intToIp(ipAddress);

        return ip;
    }

    // 这段是转换成点分式IP的码
    private static String intToIp(int ip) {
        return (ip & 0xFF) + "." + ((ip >> 8) & 0xFF) + "." + ((ip >> 16) & 0xFF) + "." + (ip >> 24 & 0xFF);
    }

    private static String[] platforms = {
            "http://pv.sohu.com/cityjson",
            "http://pv.sohu.com/cityjson?ie=utf-8",
            "http://ip.chinaz.com/getip.aspx"
    };

    public static String getOutNetIP(Context context, int index) {
        if (index < platforms.length) {
            BufferedReader buff = null;
            HttpURLConnection urlConnection = null;
            try {
                URL url = new URL(platforms[index]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.setReadTimeout(5000);// 读取超时
                urlConnection.setConnectTimeout(5000);// 连接超时
                urlConnection.setDoInput(true);
                urlConnection.setUseCaches(false);

                int responseCode = urlConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {// 找到服务器的情况下,可能还会找到别的网站返回html格式的数据
                    InputStream is = urlConnection.getInputStream();
                    buff = new BufferedReader(new InputStreamReader(is, "UTF-8"));// 注意编码，会出现乱码
                    StringBuilder builder = new StringBuilder();
                    String line = null;
                    while ((line = buff.readLine()) != null) {
                        builder.append(line);
                    }

                    buff.close();// 内部会关闭 InputStream
                    urlConnection.disconnect();

                    Log.e("xiaoman", builder.toString());
                    if (index == 0 || index == 1) {
                        // 截取字符串
                        int satrtIndex = builder.indexOf("{");// 包含[
                        int endIndex = builder.indexOf("}");// 包含]
                        String json = builder.substring(satrtIndex, endIndex + 1);// 包含[satrtIndex,endIndex)
                        JSONObject jo = new JSONObject(json);
                        String ip = jo.getString("cip");

                        return ip;
                    } else if (index == 2) {
                        JSONObject jo = new JSONObject(builder.toString());
                        return jo.getString("ip");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return getInNetIp(context);
        }
        return getOutNetIP(context, ++index);
    }

    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * To byte array byte [ ].
     *
     * @param hexString the hex string
     * @return the byte [ ]
     */
    public static byte[] toByteArray(String hexString) {
        if (hexString == null) {
            return null;
        }
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() >> 1];
        int index = 0;
        for (int i = 0; i < hexString.length(); i++) {
            if (index > hexString.length() - 1) {
                return byteArray;
            }
            byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
            byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
            byteArray[i] = (byte) (highDit << 4 | lowDit);
            index += 2;
        }
        return byteArray;
    }


    /**
     * byte[] to Hex string.
     *
     * @param byteArray the byte array
     * @return the string
     */

    public static String toHexString(byte[] byteArray) {
        final StringBuilder hexString = new StringBuilder("");
        if (byteArray == null || byteArray.length <= 0) {
            return null;
        }
        for (int i = 0; i < byteArray.length; i++) {
            int v = byteArray[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                hexString.append(0);
            }
            hexString.append(hv);
        }
        return hexString.toString().toLowerCase();
    }

    public static String map2Json(Map<String, String> paramMap) {
        StringBuilder localStringBuilder = new StringBuilder();
        Iterator<String> localIterator = paramMap.keySet().iterator();

        while (localIterator.hasNext()) {
            String str = localIterator.next();
            localStringBuilder.append(",\"" + str.trim() + "\":\"" + ((String) paramMap.get(str)) + "\"");
        }
        if (localStringBuilder.length() > 0) {
            localStringBuilder.deleteCharAt(0);
        }
        String res = "{" + localStringBuilder.toString() + "}";
        Log.i("返回内容：", res);
        return res;
    }

    public static boolean bytesToImageFile(byte[] bytes, String path) {
        try {
            File file = new File(path);
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(bytes, 0, bytes.length);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static Bitmap base64ToBitmap(String base64Data, int quality) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        Bitmap bmp = null;
        try {
            bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
        return bmp;
    }

    public static String bitmapToJpgBs(Bitmap bm) {
        if (bm != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            //InputStream isBm = new ByteArrayInputStream(baos.toByteArray());
            return Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP);
        }
        return "";
    }

    //判断字符串是否是整数
    public static boolean isNumeric(String s) {
        if (s != null && !"".equals(s.trim())) {
            return s.matches("^[0-9]*$");
        } else {
            return false;
        }
    }

}
